<template>
    <!--周月年  -->
    <div
        class="public-title"
        style="display: flex; align-items: center; justify-content: center; position: relative"
        :style="{ minHeight: props.showList ? '30px' : '' }"
    >
        <a-radio-group v-model:value="active" button-style="solid" @change="changeType" v-if="showStatus && props.showList">
            <a-radio-button v-if="props.showOne" :value="1">日</a-radio-button>
            <a-radio-button :value="2">周</a-radio-button>
            <a-radio-button :value="3">月</a-radio-button>
            <a-radio-button :value="4">年</a-radio-button>
        </a-radio-group>
        <div v-if="props.showList" class="right-d" @click="changeShowStatus">
            <img :src="showStatus ? listImg : chartImg" alt="" />
            {{ showStatus ? '列表展示' : '图表展示' }}
        </div>
    </div>

    <div
        class="public-title"
        style="display: flex; justify-content: center; margin-top: 20px; align-items: center; position: relative"
        :style="{ minHeight: props.showList ? '' : '30px' }"
    >
        <!--   锻炼类型-->
        <div
            class="fff"
            style="position: absolute; left: 10px; display: flex; align-items: center; color: #fff; margin-bottom: 10px"
            v-if="!props.showList"
        >
            锻炼类型：
            <a-select
                v-model:value="motionType"
                class="type-select"
                :field-names="montionFieldNames"
                :options="selectOptions"
                @change="changeSelect"
            ></a-select>
        </div>
        <!--日期-->
        <div style="display: flex; font-size: 20px; align-items: center; gap: 10px" v-if="showStatus && props.showList">
            <a-button class="btn" type="primary" size="small" @click="changeDate('0')">
                <LeftOutlined class="icon" style="color: #fff" />
            </a-button>
            <div style="position: relative">
                <a-date-picker
                    ref="datePicker"
                    v-model:value="dateInfo"
                    :disabledDate="(current) => current > new Date()"
                    :format="rType()"
                    :picker="getP()"
                    @change="changeValue"
                    :allow-clear="false"
                    style="opacity: 0; z-index: 99; position: absolute; top: 0; left: 0"
                >
                    <template #dateRender="{ current }">
                        <div class="ant-picker-cell-inner" :class="[getBg(current) ? 'bgc' : '']">
                            {{ current.date() }}
                        </div>
                    </template>
                </a-date-picker>
                <div style="z-index: 1; min-width: 150px; text-align: center; color: #fff">{{ getDateFormat(dateInfo) }}</div>
            </div>
            <a-button class="btn" type="primary" :disabled="!isRight" size="small" @click="changeDate('1')">
                <RightOutlined class="icon" style="color: #fff" />
            </a-button>
        </div>
    </div>
</template>
<script setup lang="ts">
    import { computed, nextTick, onMounted, ref } from 'vue';
    import { RightOutlined, LeftOutlined } from '@ant-design/icons-vue';

    import chartImg from '/@/assets/images/chart.png';
    import listImg from '/@/assets/images/list.png';
    import dayjs from 'dayjs';
    import { propTypes } from '/@/utils/propTypes';
    import { userDataDayByYearApi } from '/@/components/secondaryScreen/secondMap/secondMapApi.ts';
    import { getCodeInfo, montionFieldNames } from '/@/api/dictCode.ts';

    const props = defineProps({
        showOne: propTypes.bool.def(true),
        showList: propTypes.bool.def(true),
        keyType: propTypes.string.def(''),
        userId: propTypes.string.def(''),
    });
    const selectOptions = ref([]);
    onMounted(() => {
        getOptions();
    });

    async function getOptions() {
        try {
            const { code, result } = await getCodeInfo();
            if (code == 0) {
                nextTick(() => {
                    selectOptions.value = result?.records;
                });
            }
        } catch {}
    }

    const emit = defineEmits(['changeV', 'changeShowStatus', 'changeM']);

    const active = ref(props.showOne ? 1 : 2);
    const showStatus = ref(true);
    const dateInfo = ref(dayjs());
    const isRight = computed(() => dayjs(dateInfo.value).format('YYYY-MM-DD') != dayjs().format('YYYY-MM-DD'));

    const motionType = ref();

    const dateFormat = 'YYYY-MM-DD';
    const weekFormat = 'YYYY-MM-DD';
    const monthFormat = 'YYYY-MM';

    let searchYear = dayjs().format('YYYY');

    const infoData = ref([]);

    const customWeekStartEndFormat = (value) =>
        `${dayjs(value).startOf('week').format(weekFormat)} ~ ${dayjs(value).endOf('week').format(weekFormat)}`;

    function getInfoByDayOrMonth() {
        let params = {
            userId: props.userId,
            type: props.keyType,
            year: searchYear,
        };
        userDataDayByYearApi(params)
            .then((res) => {
                infoData.value = res?.result?.month;
            })
            .catch(() => {});
    }

    getInfoByDayOrMonth();

    function getBg(c) {
        for (let i = 0; i < infoData.value.length; i++) {
            if (infoData.value[i].month === dayjs(c).format('MM') * 1) {
                if (active.value === 3) {
                    return true;
                } else {
                    for (let j = 0; j < infoData.value[i].day.length; j++) {
                        if (dayjs(c).format('DD') * 1 === infoData.value[i].day[j]) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    function rType() {
        switch (active.value) {
            case 1:
                return dateFormat;
            case 2:
                return customWeekStartEndFormat(dateInfo.value);
            case 3:
                return monthFormat;
            case 4:
                return 'YYYY';
        }
        return '';
    }

    function getP() {
        switch (active.value) {
            case 2:
                return 'week';
            case 3:
                return 'month';
            case 4:
                return 'year';
        }
        return '';
    }

    function changeShowStatus() {
        showStatus.value = !showStatus.value;
        emit('changeShowStatus', showStatus.value);
    }

    function changeType() {
        emit('changeV', { type: active.value, value: getDateFormat(dateInfo.value) });
    }

    function changeValue() {
        if (searchYear !== dayjs(dateInfo.value).format('YYYY')) {
            searchYear = dayjs(dateInfo.value).format('YYYY');
            getInfoByDayOrMonth();
        }
        emit('changeV', { type: active.value, value: getDateFormat(dateInfo.value) });
    }

    function changeSelect() {
        emit('changeM', motionType.value);
    }

    function getDateFormat(v) {
        return active.value === 2 ? customWeekStartEndFormat(v) : dayjs(v).format(rType());
    }

    function weekNext(x, data) {
        let d = dayjs(getDateFormat(data).substring(getDateFormat(data).indexOf('~') + 2));

        return x.diff(d, 'day') < 0;
    }

    function changeDate(type) {
        const x = dayjs(dateInfo.value);
        if (searchYear !== dayjs(x).format('YYYY')) {
            searchYear = dayjs(x).format('YYYY');
            getInfoByDayOrMonth();
        }
        const y = dayjs();
        if (
            type === '1' &&
            ((active.value === 1 && x.diff(y, 'day') === 0) ||
                (active.value === 2 && weekNext(y, dateInfo.value)) ||
                (active.value === 3 && x.diff(y, 'month') === 0) ||
                (active.value === 4 && x.diff(y, 'year') === 0))
        )
            return;
        switch (active.value) {
            case 1:
                type === '0' ? (dateInfo.value = dayjs(dateInfo.value).subtract(1, 'day')) : (dateInfo.value = dayjs(dateInfo.value).add(1, 'day'));
                break;
            case 2:
                type === '0' ? (dateInfo.value = dayjs(dateInfo.value).subtract(1, 'week')) : (dateInfo.value = dayjs(dateInfo.value).add(1, 'week'));
                break;
            case 3:
                type === '0'
                    ? (dateInfo.value = dayjs(dateInfo.value).subtract(1, 'month'))
                    : (dateInfo.value = dayjs(dateInfo.value).add(1, 'month'));
                break;
            case 4:
                type === '0' ? (dateInfo.value = dayjs(dateInfo.value).subtract(1, 'year')) : (dateInfo.value = dayjs(dateInfo.value).add(1, 'year'));
                break;
        }
        changeValue();
    }
</script>
<style scoped lang="less">
    .ant-radio-button-wrapper {
        padding: 0 30px;
    }

    .right-d {
        position: absolute;
        border: 1px solid #e6e6e6;
        right: 20px;
        border-radius: 50px;
        padding: 3px 20px 3px 30px;
        display: flex;
        align-items: center;
        cursor: pointer;
        color: #5087ec;
    }

    img {
        width: 20px;
        height: 20px;
        margin-right: 10px;
    }

    :deep(.ant-select) {
        width: 200px;
    }

    .bgc {
        border: 1px solid #1890ff;
        border-radius: 50px;
    }

    .btn {
        .icon {
            color: #fff !important;
            height: 20px;
            line-height: 20px;
        }
    }

    .public-title {
        :deep(.ant-btn-primary[disabled], .ant-btn-primary[disabled]:hover, .ant-btn-primary[disabled]:focus, .ant-btn-primary[disabled]:active) {
            color: rgba(0, 0, 0, 0.25);
            border-color: #92bfe9;
            background: #92bfe9;
            text-shadow: none;
            box-shadow: none;
        }
    }
</style>